const fs = require("fs");
const path = require("path");

async function countFiles(dirPath) {
  let count = 0;

  async function walkDirectory(directory) {
    try {
      const files = await fs.promises.readdir(directory, {
        withFileTypes: true,
      });

      for (const file of files) {
        const filePath = path.join(directory, file.name);
        if (file.isDirectory()) {
          // 如果是目录，则递归调用
          await walkDirectory(filePath);
        } else {
          // 如果是文件，则计数加一
          count++;
        }
      }
    } catch (err) {
      console.error(`读取目录出错: ${directory}`, err);
    }
  }

  await walkDirectory(dirPath);
  return count;
}

// 使用示例
const directoryPath = "./"; // 替换为你要统计的目录路径
countFiles(directoryPath)
  .then((totalFiles) => {
    console.log(`总文件数量: ${totalFiles}`);
  })
  .catch((err) => {
    console.error("发生错误:", err);
  });
